import { ApartmentOutlined } from '@ant-design/icons';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { i18n, nmAppErrorLog, setObject } from '@app-nextmesh/common/utils';
import { showLoading } from '@app-nextmesh/components';
import {
  FormField,
  FormNativeSelect,
} from '@app-nextmesh/components/Forms/components';
import { makeDefaultForm } from '@app-nextmesh/components/Forms/components/utils';
import { ConditionType, ISelectOption } from '@app-nextmesh/components/types';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import { AmcaxProp, ISimulationPlugin } from '@app-nextmesh/types';
import { Button, Modal } from 'antd';
import { useEffect, useState } from 'react';
import { getEmptySimulation } from '../../../LeftPanel/data';
import {
  getDefaultCondition,
  getSimulationFormFormat,
  SimuTypeOptions,
} from '../../../LeftPanel/SimulationMenus';

interface IProps {
  count: number;
  onOk: (newData: any) => void;
  onClose: () => void;
}

export default function SimulationAddDialog({ count, onOk, onClose }: IProps) {
  const [data, setData] = useState(getEmptySimulation());
  const [isModalOpen, setIsModalOpen] = useState(false);
  const plugins: ISimulationPlugin[] = useProjectStore(
    (state) => state.projectInfo?.simulationPlugins,
  );
  const [supportedPlugins, setSupportedPlugins] = useState<ISelectOption[]>([]);

  useEffect(() => {
    const newData = { ...data };
    // 默认 仿真类型
    const simuType = SimuTypeOptions[0].value;
    newData.simuType = simuType;
    newData.name = `${i18n.t(simuType)}${count + 1}`;
    const firstPlugin = updateSupportedPlugins(simuType);
    newData.simuPlugin = firstPlugin;
    setData(newData);

    showModal();
  }, [count]);

  // 更新名字
  const getName = (name) => {
    let label = name;
    if (name === '流体力学C') {
      label = 'CFX';
    } else if (name === '结构力学N') {
      label = 'Nastran';
    } else if (name === 'Galois') {
      label = 'NextAirfoilCFD';
    }
    return label;
  };

  /**
   * 更新当前选中的仿真支持的插件列表，并返回第一个插件名称
   * @param simuType
   * @returns
   */
  const updateSupportedPlugins = (simuType: string) => {
    // 根据 仿真类型，筛选支持的插件
    const newPlugins = plugins?.filter((p) => p?.support?.includes(simuType));
    if (newPlugins?.length > 0) {
      setSupportedPlugins(
        newPlugins.map<ISelectOption>((p) => ({
          label: getName(p.name),
          value: p.name,
        })),
      );
      return newPlugins[0].name;
    }
    return undefined;
  };
  const handleInputChange = (
    name: 'simuType' | 'simuPlugin',
    value: string,
  ) => {
    const newData = { ...data };
    setObject(newData, name, value);
    if (name === 'simuType') {
      // 添加时，自动设置名称
      let title = newData.name;
      title = `${i18n.t(value)}${count + 1}`;
      newData.name = title;
      // 自动选择第一个支持的插件
      newData.simuPlugin = updateSupportedPlugins(value);
    }
    setData(newData);
  };
  const handleOk = async () => {
    const hide = showLoading();
    try {
      if (!data.simuType || !data.simuPlugin) {
        MessageTip.error(i18n.t('pleaseSelectSimTypeAndPlugin'));
        return;
      }
      data.condition = getDefaultCondition(
        `${data.simuType}.${data.simuPlugin}`,
      );

      // TODO 特殊处理，如果插件是 结构力学N，则添加一个默认的parameterUnits
      if (data.simuPlugin === '结构力学N') {
        const key = 'parameterUnits';
        const puFormat = getSimulationFormFormat(
          `${data.simuType}.${data.simuPlugin}.${key}`,
        );
        const children = Object.keys(puFormat)
          .filter((k) => k !== AmcaxProp)
          .map((k) => {
            const child = makeDefaultForm(puFormat[k]);
            child[ConditionType] = k;
            return child;
          });
        data.condition[key] = children;
      }

      const rspData = await documentV2.addSimulation(data);
      setIsModalOpen(false);
      onOk(rspData);
    } catch (error) {
      nmAppErrorLog('SimulationAddDialog', 'handleOk', error);
    } finally {
      hide();
    }
  };
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    onClose();
  };
  return (
    <Modal
      title={
        <div>
          <ApartmentOutlined style={{ marginRight: 10, color: '#e0893d' }} />
          {i18n.t('createSimulation')}
        </div>
      }
      closable={false}
      open={isModalOpen}
      footer={[
        <Button
          key='back'
          onClick={handleCancel}>
          取消
        </Button>,
        <Button
          key='submit'
          type='primary'
          onClick={handleOk}>
          创建
        </Button>,
      ]}>
      <FormField label={i18n.t('simulationType')}>
        <FormNativeSelect
          value={data.simuType}
          options={SimuTypeOptions}
          onChange={(value) => handleInputChange('simuType', value as string)}
        />
      </FormField>
      <FormField label={i18n.t('simulationPlugin')}>
        <FormNativeSelect
          value={data.simuPlugin}
          options={supportedPlugins}
          onChange={(value) => handleInputChange('simuPlugin', value as string)}
        />
      </FormField>
    </Modal>
  );
}
